package com.tsingteng.cosfun.utils;

import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 描述 :线程池的工具类
 * 创建人: 肖利.
 * 时间:2018/11/8
 * qq(872179966)
 */

public class ThreadPoolUtils {

    ThreadPoolExecutor mThreadPoolExecutor;
    private static ThreadPoolUtils mInstance = null;
    private int corePoolSize;
    private int maximumPoolSize;
    private long keepAliveTime;




    private ThreadPoolUtils(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.keepAliveTime = keepAliveTime;
    }

    public static ThreadPoolUtils getmInstance() {
        if (mInstance==null) {
            synchronized (ThreadPoolUtils.class) {
                if (mInstance == null) {
                    mInstance = new ThreadPoolUtils(1, 2, 3000);
                }
            }
        }
        return mInstance;
    }



    private ThreadPoolExecutor initExecutor() {
        if(mThreadPoolExecutor == null) {
            synchronized(ThreadPoolUtils.class) {
                if(mThreadPoolExecutor == null) {

                    TimeUnit unit =  TimeUnit.MILLISECONDS;
                    ThreadFactory threadFactory = Executors.defaultThreadFactory();
                    RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
                    LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();

                    mThreadPoolExecutor = new ThreadPoolExecutor(
                            corePoolSize,//核心线程数
                            maximumPoolSize,//最大线程数
                            keepAliveTime,//保持时间
                            unit,//保持时间对应的单位
                            workQueue,
                            threadFactory,//线程工厂
                            handler);//异常捕获器
                }
            }
        }
        return mThreadPoolExecutor;
    }



    /**执行任务*/
    public void executeTask(Runnable r) {
        initExecutor();
        mThreadPoolExecutor.execute(r);
    }


    /**提交任务*/
    public Future<?> commitTask(Runnable r) {
        initExecutor();
        return mThreadPoolExecutor.submit(r);
    }

    /**删除任务*/
    public void removeTask(Runnable r) {
        initExecutor();
        mThreadPoolExecutor.remove(r);
    }


}
